import React, {PureComponent} from 'react';
import {
  StyleSheet,
  BackHandler,
  AppState,
  Platform,
  DeviceEventEmitter,
  ScrollView,
  View,
  Alert,
  Linking,
  RefreshControl,
  SafeAreaView,
} from 'react-native';
import Toast from 'react-native-root-toast';
import StatusBarComponent from '../../components/StatusBarComponent';
import Loading from '../../components/Loading';
import {showToast} from '../../components/Toast';
import store from '../../redux/store';
import {I18n} from '../../config/language/i18n';
import MyAlert from '../../components/MyAlert';
import StorageManager, {USER_INFO, METAMASK_ADDRESS} from '../../storage';
import {setRoomKey} from '../../redux/action/index';
import {queryChannel} from '../../api/channel';

let lastBackPressed = 0;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

// 所有继承该组件的组件，重写该组件方法请先运行super.funcName()
export default class BaseComponent extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      isShowLoading: false,
      loadingText: 'Loading',
      isShowAlert: false,
      alertContent: '',
      scollEnabled: false,
      okTitle: undefined,
      alertOkPress: undefined,
      alertCancelPress: undefined,
      cancelTitle: undefined,
      bgDismissEnable: false,
    };

    this.currentRouteName = '';
    this._showAlert = this._showAlert.bind(this);

    this._addEventListener = this._addEventListener.bind(this);
    this._removeEventListener = this._removeEventListener.bind(this);
    this._showLoading = this._showLoading.bind(this);
    this._hideLoading = this._hideLoading.bind(this);
    this._initData = this._initData.bind(this);
    this._onBackPressed = this._onBackPressed.bind(this);
    this._barStyle = 'light-content';
    this._isMounted = false;
  }

  checkWalletConnect = () => {
    if (
      !store.getState().User.userInfo.metamaskAddress &&
      !store.getState().User.userInfo.disableGift
    ) {
      this._showAlert({
        content: 'Please connect to wallet',
        okTitle: 'Next',
        alertOkPress: () => {
          this.props.navigation.navigate('NewWallet');
        },
      });
      return false;
    }

    return true;
  };

  // 设置StatusBar的barStyle为light-content,默认为dark-content
  _setStatusBarStyleLight() {
    this._barStyle = 'light-content';
  }

  _setStatusBarStyleDark() {
    this._barStyle = 'dark-content';
  }

  componentDidMount() {
    this._addEventListener();
    this._initData();
  }

  UNSAFE_componentWillMount() {
    this._isMounted = true;
  }

  componentWillUnmount() {
    this._removeEventListener();
    this._isMounted = false;
  }

  // 初始化数据
  _initData = () => {};

  // 添加事件监听
  _addEventListener() {
    this.netRequestErrHandler = DeviceEventEmitter.addListener(
      'netRequestErr',
      this._netRequestErr,
    ); // 网络异常情况监听
    this.authErrListener = DeviceEventEmitter.addListener(
      'AuthenticationError',
      this._authErr,
    );

    this.quitRoomEmitter = DeviceEventEmitter.addListener(
      'quitRoomPage',
      this.quitRoomPage,
    );

    this.quitRoomEmitter = DeviceEventEmitter.addListener(
      'enterRoom',
      this.enterRoom,
    );

    AppState.addEventListener('change', this._backgroundStateEmitter);
  }

  // 移除事件监听
  _removeEventListener() {
    if (this.netRequestErrHandler) {
      this.netRequestErrHandler.remove();
    }

    if (this.authErrListener) {
      this.authErrListener.remove();
    }

    if (this.quitRoomEmitter) {
      this.quitRoomEmitter.remove();
    }

    if (this.enterRoomEmitter) {
      this.enterRoomEmitter.remove();
    }

    //移除监听
    // this._handleAppStateChange.remove()
  }

  quitRoomPage = () => {
    console.log('返回');
    console.log(store.getState().Layout.roomKey);

    //返回到主页
    if (store.getState().Layout.roomKey != '') {
      console.log('执行返回');
      this.props.navigation.goBack(store.getState().Layout.roomKey);
      store.dispatch(setRoomKey(''));
    } else {
      console.log('未找到返回的key');
      this.props.navigation.goBack();
    }

    DeviceEventEmitter.emit('popRoom');
  };

  enterRoom = () => {
    console.log('进入房间');

    if (!this.props.navigation) {
      return;
    }

    let stack = store.getState().Layout.navigationStack;
    console.log(stack);

    //如果有Room,并且不是当前页则返回
    if (stack.some((item) => item.routeName == 'Room')) {
      let roomIdx = stack.length;
      stack.map((item, idx) => {
        console.log(item);
        if (idx == roomIdx + 1) {
          console.log('返回room页面');
          this.props.navigation.goBack(item.key);
        } else if (item.routeName == 'Room') {
          roomIdx = idx;
        }
      });
    } else {
      console.log('进入room房间');

      this.props.navigation.navigate('Room', {
        from: 'other',
      });

      // this._showLoading();
      // let userInfo = store.getState().User.userInfo;
      // queryChannel({
      //   userToken: userInfo.token,
      //   channelId: userInfo.currentChannel,
      // })
      //   .then(async (res) => {

      //     console.log(res);

      //     this._hideLoading();

      //     this.props.navigation.navigate('Room', {
      //       from: 'other',
      //     });
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //     this._hideLoading();
      //     // this.onRefresh();
      //     // this._showAlert(I18n.t('home.disbanded'), null, () => {
      //     //   this.onRefresh();
      //     // });
      //   });
    }
  };

  _authErr = () => {
    StorageManager.remove(USER_INFO);
    showToast(I18n.t('common.auth_err'), Toast.positions.TOP);
    this.props.navigation.navigate('Login');
  };

  // 显示Loading
  _showLoading(text = 'Loading', showed) {
    if (this._isMounted) {
      this.setState({isShowLoading: true, loadingText: text}, showed);
    }
  }

  // 隐藏Loading
  _hideLoading(hided) {
    if (this._isMounted) {
      this.setState({isShowLoading: false}, hided);
    }
  }

  // 显示PinCode
  _showPin(showPined) {
    this.setState({isShowPin: true}, showPined);
  }

  // 隐藏PinCode
  _hidePin(hidePined) {
    this.setState({isShowPin: false}, hidePined);
  }

  // pin显示的时候，其他的modal必须关系，否则pin显示不出来
  _closeModal = () => {};

  // 渲染子组件
  renderComponent = () => {};

  _showAlert({
    content,
    okTitle,
    alertOkPress,
    cancelTitle,
    alertCancelPress,
    bgDismissEnable,
  }) {
    if (this._isMounted) {
      this.setState({
        isShowLoading: false,
        isShowAlert: true,
        alertContent: content,
        alertOkPress: alertOkPress,
        okTitle,
        cancelTitle,
        alertCancelPress: alertCancelPress,
        bgDismissEnable,
      });
    }
  }

  _hideAlert() {
    const {isShowAlert} = this.state;
    if (isShowAlert) {
      this.setState({
        isShowAlert: false,
      });
    }
  }

  // 网络请假错误回调
  _netRequestErr = (err) => {
    this._hideLoading();
    this.toast = showToast('network request err!', Toast.positions.TOP + 10);
  };

  // 点击android物理返回键的操作
  _onBackPressed = () => {
    const {navigation} = this.props;
    const {routeName} = navigation.state;
    if (
      routeName === 'FirstLaunch' ||
      routeName === 'Home' ||
      routeName === 'NewWallet'
    ) {
      // 在首页按了物理键返回,Home、FirstLaunch
      if (lastBackPressed + 2000 >= Date.now()) {
        BackHandler.exitApp();
        return false;
      }
      showToast(I18n.t('toast.exit_app'));
      lastBackPressed = Date.now();
      return true;
    } else if (routeName === 'Room') {
      return false;
    }

    navigation.goBack();
    return true;
  };

  // 接收前台后台切换的监听
  _backgroundStateEmitter = (data) => {};

  _verifyIdentidy(success) {}

  _onRefresh = () => {
    console.log('刷新');
  };

  alertBgDimiss = () => {
    this.setState({
      isShowAlert: false,
    });
  };

  render() {
    let {
      isShowAlert,
      alertContent,
      isShowLoading,
      loadingText,
      alertOkPress,
      okTitle,
      alertCancelPress,
      cancelTitle,
      bgDismissEnable,
    } = this.state;

    return (
      <View
        style={{
          backgroundColor: '#FFCB26',
          flex: 1,
          // marginBottom: showRoomWidget ? 70 : 0,
        }}>
        <StatusBarComponent barStyle={this._barStyle} />
        {this.renderComponent()}
        {isShowAlert === undefined ? null : (
          <MyAlert
            modalVisible={isShowAlert}
            content={alertContent}
            okTitle={okTitle}
            cancelTitle={cancelTitle}
            bgDismissEnable={bgDismissEnable}
            bgDimiss={this.alertBgDimiss}
            okPress={() => {
              this._hideAlert();
              alertOkPress && alertOkPress();
            }}
            cancelPress={() => {
              this._hideAlert();
              alertCancelPress && alertCancelPress();
            }}
          />
        )}
        {isShowLoading === undefined ? null : (
          <Loading visible={isShowLoading} text={loadingText} />
        )}
      </View>
    );
  }
}
